var config = require ("../config")
var util = require ("../utils/util")

//默认上传成功回调
var default_success = function(res)
{
  utils.showSuccess("上传成功");
}

//默认上传失败回调
var default_fail = function(res)
{
  utils.showModel("上传失败", res);
}


//计算签名
var getAuthorization = function (options, callback) {
  wx.request({
    method: 'GET',
    url: config.coscignatureUrl, // 服务端签名，参考 server 目录下的两个签名例子
    data: {
      method: options.method,
      pathname: options.pathname,
    },
    dataType: 'json',
    success: function (result) {
      callback(result.data);
    }
  });
};

var uploadFile = function (filePath, options) {
  var success = options.success || default_success;
  var fail = options.fail || default_fail;

  var fileName = filePath.substr(filePath.lastIndexOf('/') + 1);

  console.log(config.uploadUrl_img);  
  getAuthorization({ method: 'post', pathname: '/product' }, function (AuthData) {
    var requestTask = wx.uploadFile({
      url: config.uploadUrl_img,
      name: 'file',//这里一定要这个名字, 别问为什么，划重点背下来，考！
      filePath: filePath,
      formData: {
        'key': fileName,
        'success_action_status': 200,
        'Signature': AuthData.Authorization,
        'x-cos-security-token': AuthData.XCosSecurityToken,
        'Content-Type': '',
      },
      success: function (res) {
        var Location = config.bucketRoot + "/" + fileName;
        if (res.statusCode === 200) {
          console.log("======================1"+res.statusCode);
          success(Location)
        } 
        else 
        {
          console.log("======================2"+res.statusCode);
          fail(filePath);
        }
      },
      fail: function (res) {
        fail(filePath);
      }
    });

    requestTask.onProgressUpdate(function (res) {
      console.log('正在进度:', res);
    });
  });
};

var uploadFiles = function(filePaths, options)
{
  var success = options.success || default_success;
  var fail = options.fail || default_fail;

  if(filePaths == null || filePaths.lenfth < 1)
  {
    console.error("uploadFiles -> 参数错误");
    return;
  }

  util.showBusy("上传中...");

  var successPaths = new Array()
  var failPaths = new Array();

  var ifComplete = function()
  {
    if((successPaths.length + failPaths.length) == filePaths.length)
    {
      var ret = 
      {
        successPaths:successPaths,
        failPaths:failPaths,
      }

      success(ret);
      console.log("上传完成");
      util.showSuccess("上传完成");
      return true;
    }
    
    console.log("上传还为完成");
    return false;
  }

  var completeOptions =
  {
    success:function(res)
    {
      successPaths.push(res);
      ifComplete();
    },
    fail:function(res)
    {
      failPaths.push(res);
      ifComplete();
    }
  }

  for(var i = 0; i < filePaths.length; i++)
  {
    uploadFile(filePaths[i], completeOptions);
  }
}

module.exports = 
{
  uploadFile,
  uploadFiles
}